<?php
use Base\AdminController;
use Illuminate\Support\Str;

class AppController extends AdminController
{
    protected string $table = 'applications';

    protected string $model = "application";

    #[NoReturn] public function init(): void
    {
        $this->routeWhiteLst = ['app@index','app@add','app@edit','app@del'];
        parent::init();
    }

    /**
     * 修改
     * @return void
     */
    protected function update(): void
    {
        if (!extension_loaded("yaconf")) {
            $this->apiError("请先安装yaconf扩展");
        }
        try {
            $params  = Request::all();
            $this->cleanCache();
            $params['create_author'] = $this->user['nickname'];
            if (Request::input("id") !== null) {
                App::make($this->getModelMame())->where("id",Request::input("id"))->update($params);
                $this->apiSuccess([],"更新成功",20000);
            }else {
                $config_dir = ini_get("yaconf.directory");
                $params['app_id'] = date("YmdHis");
                $params['uuid'] = (string)Str::uuid();
                $params['created_at'] = date("Y-m-d H:i:s");
                if (DB::schema()->hasColumn($this->table, "org_id")) {
                    $params['org_id'] = $this->org['id'];
                }
                if (DB::schema()->hasColumn($this->table, "user_id")) {
                    $params['user_id'] = $this->member_id;
                }
                $res =  App::make($this->getModelMame())->insertGetId($params);
                $info =  App::make($this->getModelMame())->where('id',$res)->first();
                file_put_contents($config_dir."/".$info['app_id'].".ini", "");
                $this->apiSuccess( $info->toArray(),"新增成功",20000);
            }
        } catch (Exception $e) {
            $this->apiError($e->getMessage());
        }
    }
}
